<template>
    <section>
        <el-table header-cell-class-name="text-black" row-key="id" :data="state.data" border height="calc(100vh - 120px)"
            style="width: 99%" :tree-props="{ children: 'data' }" @row-dblclick="showEditProduct">
            <el-table-column prop="pIp" label="IP" />
            <el-table-column prop="name" label="商品" />
            <el-table-column align="center" prop="orderDate" label="进货时间" width="150">
                <template #default="scope">
                    <p v-if="scope.row.orderDate" class="text-center">
                        {{ dayjs(scope.row.orderDate).format("YYYY-MM-DD HH:mm") }}
                    </p>
                    <p v-else></p>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="buyPrice" label="进价" width="100">
                <template #default="scope">
                    <p v-if="scope.row.buyPrice" class="text-center text-[#ff4d4d]">
                        {{ scope.row.buyPrice }}￥
                    </p>
                    <p v-else></p>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="sellPrice" label="售价" width="100">
                <template #default="scope">
                    <p v-if="scope.row.sellPrice && scope.row.sellPrice !== '0.00'" class="text-center text-[#ff4d4d]">
                        {{ scope.row.sellPrice }}￥
                    </p>
                    <p v-else></p>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="stock" label="库存" width="120" />
            <!-- <el-table-column align="center" prop="postage" label="邮费" width="120">
                <template #default="scope">
                    <p v-if="scope.row.postage" class="text-center text-blue">
                        {{ scope.row.postage }}￥
                    </p>
                    <p v-else></p>
                </template>
            </el-table-column> -->
            <el-table-column sortable align="center" prop="sum" label="总价值" width="120">
                <template #default="scope">
                    <p v-if="scope.row.sum" class="text-center text-blue font-bold">
                        {{ scope.row.sum }}￥
                    </p>
                    <p v-else></p>
                </template>
            </el-table-column>
            <el-table-column sortable align="center" prop="sum" label="预计利润" width="120">
                <template #default="scope">
                    <p v-if="scope.row.sum" class="text-center text-[#ff4d4d] font-bold">
                        {{ scope.row.profit }}￥
                    </p>
                    <p v-else></p>
                </template>
            </el-table-column>
        </el-table>

        <el-row class="my-[12px] mr-[20px] h-[40px]" justify="end">
            <el-col>
                <ul class="flex flex-1 justify-end items-center font-bold">
                    <p class="mx-[10px]">库存剩余：<span class="text-[#ff4d4d]">
                            {{ (state.totalObj?.stock || 0) + ' ' }}</span>件
                    </p>
                    <p class="mx-[10px]">总价值：<span class="text-[#ff4d4d]">
                            {{ state.totalObj?.sum || 0 }}￥</span>
                    </p>
                    <p class="mx-[10px] relative">
                        预计利润：
                        <span class="text-[#ff4d4d]">{{ state.totalObj?.profit || 0 }}￥</span>
                        <span class="block absolute right-[5px] top-[20px] text-[8px] text-blue">(售价-进价)*库存</span>
                    </p>
                    <el-button type="primary" @click="loadData(true)">
                        <el-icon><i-ep-Refresh /></el-icon>&nbsp;刷新
                    </el-button>
                </ul>
            </el-col>
        </el-row>

        <operate-product v-if="state.showEditProduct" v-model="state.showEditProduct" :source="state.source"
            :status="state.status" :category="state.category" :ip="state.ip" v-model:pageType="state.pageType"
            v-model:currentProduct="state.currentProduct" :refresh="loadData" />
    </section>
</template>

<script lang='ts' setup>
import { Product, Stock } from '@/components/product/type';
import Decimal from 'decimal.js';
import { dayjs } from "element-plus";

type Count = {
    stock: number,
    sum: number,
    profit: number,
}

type StockProduct = Product & Count

type ProductStock = {
    id?: string,
    pIp?: string,
    buyPrice?: number | string,
    sellPrice?: number | string,
    data: StockProduct[]
} & Count

type Props = {
    data: ProductStock[],
    totalObj: Count | null,
    category: Array<{ key: string; value: string | number }>,
    source: Array<{ key: string; value: string | number }>,
    ip: Array<{ key: string; value: string | number }>,
    status: Array<{ key: string; value: string | number }>,
    showEditProduct: boolean,
    currentProduct: StockProduct | null,
    pageType: number,
}
const state = reactive<Props>({
    data: [],
    totalObj: null,

    category: [],
    source: [],
    ip: [],
    status: [],

    showEditProduct: false,
    pageType: 1,
    currentProduct: null,
})

const calculateDecimal = (_: StockProduct) => {
    const sellPrice = new Decimal(_.sellPrice).toNumber()
    const buyPrice = new Decimal(_.buyPrice).toNumber()
    let profit = 0, sum = 0
    if (sellPrice && buyPrice) {
        profit = new Decimal(_.sellPrice).sub(_.buyPrice).mul(_.stock).toNumber()
    }
    if (sellPrice) {
        sum = new Decimal(_.sellPrice).mul(_.stock).toNumber()
    }
    return { sum, profit, sellPrice }
}

const createOutRecord = (source: ProductStock | undefined, _: StockProduct): ProductStock => {
    const { sum, profit } = calculateDecimal(_)
    _.sum = sum
    _.profit = profit
    if (source) {
        source.stock += _.stock
        source.sum = new Decimal(source.sum).add(sum).toNumber()
        source.profit = new Decimal(source.profit).add(profit).toNumber()
        source.data = [...source.data, _]
        return source
    }
    const temp = _.pIp
    const obj: ProductStock = {
        id: Utils.guid(),
        pIp: temp,
        stock: _.stock,
        sum,
        profit,
        data: [_]
    }
    return obj
}

const loadData = async (showLoading?: boolean) => {
    showLoading && Utils.Modal().loading('加载中~')
    const [err, res] = await ProductService.getAllProductStock()
    showLoading && Utils.Modal().closeLoading()

    if (err) return Utils.Modal().msgError(err)
    const { data = [] } = res || {}

    const map = new Map<string, ProductStock>()
    const temp = {
        stock: 0,
        sum: 0,
        profit: 0,
    }
    data.forEach((_: StockProduct) => {
        temp.stock += _.stock
        const { sum, profit } = calculateDecimal(_)
        temp.sum = new Decimal(temp.sum).add(sum).toNumber()
        temp.profit = new Decimal(temp.profit).add(profit).toNumber()

        return map.set(_.pIp, createOutRecord(map.get(_.pIp), _))
    });

    state.data = [...map.values()]
    state.totalObj = temp
}

const loadProductCategory = async () => {
    const [err, res] = await ProductService.loadProductCategory();
    if (err) {
        return Utils.Modal().msgSuccess(err);
    }
    const { category, source, ip, status } = res.data || {};
    state.category = category;
    state.source = source;
    state.ip = ip;
    state.status = status;
};

const showEditProduct = (row: StockProduct) => {
    if (!row.name) return
    state.pageType = 1
    state.showEditProduct = true
    state.currentProduct = row
}

loadData()
loadProductCategory()
</script>

<style lang='scss' scoped></style>